package com.yjhh.chdataservice.service;

import com.google.common.collect.Lists;
import com.yjhh.chdataservice.InitDataFactory;
import com.yjhh.chdataservice.beans.*;
import com.yjhh.chdataservice.component.CommonDataComponent;
import com.yjhh.chdataservice.component.ESClientManager;
import com.yjhh.chdataservice.except.YJHHException;
import com.yjhh.chdataservice.util.CommonResultData;
import com.yjhh.chdataservice.util.DataConsts;
import com.yjhh.chdataservice.util.DataTools;
import com.yjhh.chdataservice.util.XaUtil;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.InternalDateHistogram;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.aggregations.metrics.max.InternalMax;
import org.elasticsearch.search.aggregations.metrics.max.MaxAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.prefixQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * Created by hlantian on 2017/9/26.
 * 辅助决策对象管理serviceImpl
 */
@Service
@Log4j2
public class FZJCObjServiceImpl implements FZJCObjService {

    @Autowired
    private ESClientManager esClientManager;

    @Autowired
    private InitDataFactory initDataFactory;

    @Autowired
    private CommonDataComponent commonDataComponent;

    @Value("${area.areatype}")
    private String areaType;

    @Value("${task.startyear}")
    private Integer taskStartYear;

    @Value("${task.endyear}")
    private Integer taskEndYear;

    @Override
    public CommonResultData<List<MoveDataVo>> getObjStaticsByAreaCode(String areaCode) throws YJHHException {
        DeptBean syDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);

        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(prefixQuery("deptno.keyword", syDeptInfo.getDeptno()));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize(0)
                .setQuery(areacodequery);
        TermsAggregationBuilder depts = AggregationBuilders.terms("depts");
        if (depts == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        String deptID = DataConsts.getDeptID(syDeptInfo.getDeptLevel() + 1);
        if (deptID == null || "".equals(deptID.trim())) {
            return new CommonResultData<List<MoveDataVo>>(HttpStatus.OK.value(), "no data", null);
        }
        TermsAggregationBuilder deptsAgg = depts.field(deptID).missing(DataConsts.UNKNOWN).size(100).order(Terms.Order.count(true));

        TermsAggregationBuilder removeTypeAgg = AggregationBuilders.terms("removaltype").field("removaltypeid").order(Terms.Order.count(true));

        removeTypeAgg.subAggregation(AggregationBuilders.sum("peoples").field("familyMemberCount"));
        removeTypeAgg.subAggregation(AggregationBuilders.count("familys").field("familyMemberCount"));
        deptsAgg.subAggregation(removeTypeAgg);

        searchRequestBuilder.addAggregation(deptsAgg);

        log.info("reqeust: " + searchRequestBuilder.toString());

        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        String jsonData = searchResponse.toString();
        log.info("response:" + jsonData);

        List<MoveDataVo> deptInfoVoList = parseMoveTopData(syDeptInfo.getDeptID(), jsonData, areaCode, syDeptInfo.getDeptName(), syDeptInfo.getAreaLevel());
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", deptInfoVoList);
    }

    @Override
    public CommonResultData<List<ObjRelocaSimpleInfoVo>> getPoorObjstaticsInfoByAreaCode(String areaCode) throws YJHHException {
        DeptBean syDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);

        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(prefixQuery("deptno.keyword", syDeptInfo.getDeptno()));

        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(new String[]{"relocationid", "obj_reloca_jtrk", "obj_reloca_hzxm", "removaltypename", "jd", "wd",
                "deptid", "familyMemberCount"}, null);
        searchSourceBuilder.query(areacodequery);
        FieldSortBuilder sort = new FieldSortBuilder("deptno.keyword");
        searchSourceBuilder.sort(sort);
        searchSourceBuilder.size(10000);

        searchRequestBuilder.setSource(searchSourceBuilder);

        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());

        Map<String, JSONObject> deptInfoMap = initDataFactory.getDeptInfoMap();

        List<ObjRelocaSimpleInfoVo> objRelocaSimpleInfoVos = prasePoorObjReps(areaCode, syDeptInfo, searchResponse, deptInfoMap);

        return new CommonResultData<>(HttpStatus.OK.value(), "suc", objRelocaSimpleInfoVos);
    }

    @Override
    public CommonResultData<ObjRZLResultVo> getObjMoveInPercentByAreaCode(String areaCode) throws YJHHException {
        DeptBean syDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);

        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(prefixQuery("deptno.keyword", syDeptInfo.getDeptno()));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize
                (0).setQuery
                (areacodequery);
        TermsAggregationBuilder deptsAgg = AggregationBuilders.terms("depts").field(DataConsts.getDeptName(syDeptInfo.getDeptLevel() + 1)).missing
                (DataConsts.UNKNOWN).size(100);

        //入住状态
        TermsAggregationBuilder moveUpStatus = AggregationBuilders.terms("movesupState").field("objmovesupinf.obj_movesup_state");
        deptsAgg.subAggregation(moveUpStatus);

        searchRequestBuilder.addAggregation(deptsAgg);

        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());

        List<Aggregation> aggregations = searchResponse.getAggregations().asList();

        if (aggregations == null || aggregations.size() <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }

        List<ObjRZLVo> objRZLVosTemp = new ArrayList<>();

        StringTerms stringTerms = (StringTerms) aggregations.get(0);
        for (StringTerms.Bucket bucket : stringTerms.getBuckets()) {
            ObjRZLVo objRZLVo = new ObjRZLVo();
            objRZLVo.setAreaName(bucket.getKeyAsString());

            Double totalHS = bucket.getDocCount() * 1.0;    //总户数
            Double yrzHS = 0.0;    //已入住户数
            LongTerms ruzhuTerms = (LongTerms) bucket.getAggregations().asList().get(0);
            for (LongTerms.Bucket ruzhuTermBucket : ruzhuTerms.getBuckets()) {
                String yrzHSKey = ruzhuTermBucket.getKeyAsString();   //已入住户数
                if (StringUtils.equalsIgnoreCase("1", yrzHSKey)) {
                    yrzHS = ruzhuTermBucket.getDocCount() * 1.0;
                }
            }

            BigDecimal bigDecimal = new BigDecimal((yrzHS / totalHS) * 100);
            double rzq = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            objRZLVo.setPercent(rzq);

            objRZLVosTemp.add(objRZLVo);
        }

        //按部门areacode排序
        List<DeptBean> subDeptList = commonDataComponent.getSubDeptByDeptId(syDeptInfo.getDeptID());
        List<ObjRZLVo> objRZLVos = new ArrayList<>();
        for (DeptBean deptBean : subDeptList) {
            String deptName = deptBean.getDeptName();
            ObjRZLVo objRZLVo = null;
            for (ObjRZLVo objRZLVoTemp : objRZLVosTemp) {
                if (StringUtils.equalsIgnoreCase(deptName, objRZLVoTemp.getAreaName())) {
                    objRZLVo = objRZLVoTemp;
                }
            }
            if (objRZLVo == null) {
                objRZLVo = new ObjRZLVo();
                objRZLVo.setAreaName(deptName);
                objRZLVo.setPercent(0.0);
            }
            objRZLVos.add(objRZLVo);
        }

       /* //入住率由高到低排序
        Collections.sort(objRZLVos, (ObjRZLVo o1, ObjRZLVo o2) -> {
            return o2.getPercent() >= o1.getPercent() ? 1 : -1;
        });*/

        List<String> areaNameList = new ArrayList<>();
        List<Double> percentList = new ArrayList<>();

        for (ObjRZLVo objRZLVo : objRZLVos) {
            areaNameList.add(objRZLVo.getAreaName());
            percentList.add(objRZLVo.getPercent());
        }

        return new CommonResultData<>(HttpStatus.OK.value(), "suc", new ObjRZLResultVo(areaNameList, percentList));
    }

    @Override
    public CommonResultData<ObjRZLResultVo> getObjMoveInPercentByAreaCodeReport(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        List<DeptBean> subDeptList = commonDataComponent.getSubDeptByDeptId(sysDeptInfo.getDeptID());

        //获取最大上报年月
        MaxYearMonth maxReportYearMonth = commonDataComponent.getMaxReportYearMonth(null);

        if (maxReportYearMonth == null) {
            return null;
        }

        List<ObjRZLVo> objRZLVos = new ArrayList<>();
        //获取子部门数据
        for (DeptBean deptBean : subDeptList) {
            ObjRZLVo objRZLVo = new ObjRZLVo();
            objRZLVos.add(objRZLVo);
            objRZLVo.setAreaName(deptBean.getDeptName());

            String deptID = deptBean.getDeptID();
            SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_imppr_targetdata").setTypes("imppr_targetdata")
                    .setSize(1);

            BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("deptid.keyword", deptID));
            boolQueryBuilder.must(termQuery("imptype", DataConsts.ReportRemoveType.ALL));
            boolQueryBuilder.must(termQuery("fillyear", maxReportYearMonth.getYear()));
            boolQueryBuilder.must(termQuery("fillmonth", maxReportYearMonth.getMonth()));
            searchRequestBuilder.setQuery(boolQueryBuilder);

            log.info("request=" + searchRequestBuilder.toString());
            SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
            log.info("response=" + searchResponse.toString());

            SearchHit[] searchHits = searchResponse.getHits().getHits();

            if (searchHits == null || searchHits.length <= 0) {
                objRZLVo.setPercent(0.0);
                continue;
            }

            Map<String, Object> source = searchHits[0].getSource();
            Double rzRate = DataTools.convertToDouble(source.get("rz_rate"));
            objRZLVo.setPercent(rzRate);
        }

        /*//入住率由高到低排序
        Collections.sort(objRZLVos, (ObjRZLVo o1, ObjRZLVo o2) -> {
            return o2.getPercent() >= o1.getPercent() ? 1 : -1;
        });*/

        List<String> areaNameList = new ArrayList<>();
        List<Double> percentList = new ArrayList<>();

        for (ObjRZLVo objRZLVo : objRZLVos) {
            areaNameList.add(objRZLVo.getAreaName());
            percentList.add(objRZLVo.getPercent());
        }

        return new CommonResultData<>(HttpStatus.OK.value(), "suc", new ObjRZLResultVo(areaNameList, percentList));
    }

    @Override
    public CommonResultData<ObjMoveInfoVo> getPoorObjInfoById(String id) throws YJHHException {
        //获取搬迁户基础表
        QueryBuilder idsQueryBuilder = QueryBuilders.idsQuery().addIds(id);
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setQuery
                (idsQueryBuilder);

        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());

        Map<String, JSONObject> deptInfoMap = initDataFactory.getDeptInfoMap();

        SearchHit[] hits = searchResponse.getHits().getHits();

        if (hits == null || hits.length <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }

        Map<String, Object> source = hits[0].getSource();

        Double jd = source.get("jd") == null ? null : Double.parseDouble(source.get("jd").toString());
        Double wd = source.get("wd") == null ? null : Double.parseDouble(source.get("wd").toString());
        String deptid = source.get("deptid").toString();

        JSONObject deptInfo = deptInfoMap.get(deptid);
        if (deptInfo != null && (jd == null || wd == null)) {
            String longitude = deptInfo.getString("longitude");
            jd = (StringUtils.isBlank(longitude) || StringUtils.equalsIgnoreCase("null", longitude)) ? null : Double.parseDouble(longitude);
            String latitude = deptInfo.getString("latitude");
            wd = (StringUtils.isBlank(latitude) || StringUtils.equalsIgnoreCase("null", latitude)) ? null : Double.parseDouble(latitude);
        }

        Map<String, Object> objmovesupinf = (Map<String, Object>) source.get("objmovesupinf");
        Map<String, Object> objmeasuresinfo = (Map<String, Object>) source.get("objmeasuresinfo");
        List<Map<String, Object>> objfamilyinfList = getFamilyMemberByObjId(id);

        //贫困户基础信息
        ObjBaseInfoVo objBaseInfoVo = new ObjBaseInfoVo(wd, jd,
                DataTools.convertToStr(source.get("provincename")) +
                        DataTools.convertToStr(source.get("cityname")) +
                        DataTools.convertToStr(source.get("countryname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("obj_reloca_jtyzz")),
                DataTools.convertToStr(source.get("obj_reloca_hzxm")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_jkzk"))),
                DataTools.convertToStr(source.get("obj_reloca_jtrk") == null ? source.get
                        ("familyMemberCount") : source.get("obj_reloca_jtrk")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_ldnl"))),
                DataTools.convertToStr(source.get("obj_reloca_sfzh")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_whcd"))),
                DataTools.convertToStr(source.get("obj_reloca_xb")),
                DataTools.convertToStr(source.get("relocationid")),
                DataTools.convertToStr(source.get("removaltypename")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdid")),
                StringUtils.isBlank(DataTools.convertToStr(objmovesupinf.get("pointy"))) ? 0.0 : Double
                        .parseDouble
                                (DataTools.convertToStr(objmovesupinf.get("pointy"))),
                StringUtils.isBlank(DataTools.convertToStr(objmovesupinf.get("pointx"))) ? 0.0 : Double
                        .parseDouble
                                (DataTools.convertToStr(objmovesupinf.get("pointx"))),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdmc")));

        //家庭成员信息
        Map<String, Object> objHzMap = null;
        List<FamilyMemberInfoVo> familyMemberInfoVoList = new ArrayList<>();
        for (Map<String, Object> objfamilyinfMap : objfamilyinfList) {
            FamilyMemberInfoVo familyMemberInfoVo = new FamilyMemberInfoVo(DataTools.convertToStr(objfamilyinfMap.get("familymemberid")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr
                            (objfamilyinfMap.get
                                    ("obj_relfamily_jkzk"))),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr
                            (objfamilyinfMap.get
                                    ("obj_relfamily_ldnl"))),
                    DataTools.convertToStr(objfamilyinfMap.get("obj_relfamily_name")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr
                            (objfamilyinfMap.get
                                    ("obj_relfamily_whcd"))),
                    DataTools.convertToStr(objfamilyinfMap.get("obj_relfamily_yhzgx")),
                    id);

            if (StringUtils.equalsIgnoreCase(objBaseInfoVo.getOBJ_RELOCA_SFZH(), DataTools.convertToStr(objfamilyinfMap.get("obj_relfamily_sfzh")))) {
                objHzMap = objfamilyinfMap;
            }
            familyMemberInfoVoList.add(familyMemberInfoVo);
        }

        if (objHzMap != null) {
            objBaseInfoVo.setOBJ_RELOCA_XB(DataTools.convertToStr(objHzMap.get("obj_relfamily_xb")));
            objBaseInfoVo.setOBJ_RELOCA_YHYDBH(DataTools.convertToStr(objHzMap.get("obj_reloca_yhydbh")));
            objBaseInfoVo.setOBJ_RELOCA_WHCD(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_whcd"))));
            objBaseInfoVo.setOBJ_RELOCA_LDNL(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_ldnl"))));
            objBaseInfoVo.setOBJ_RELOCA_JKZK(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_jkzk"))));
        }

        //搬迁信息
        MovesupInfoVo movesupInfoVo = new MovesupInfoVo(DataTools.convertToStr(objmovesupinf.get("provincename")) +
                DataTools.convertToStr(objmovesupinf.get("cityname")) +
                DataTools.convertToStr(objmovesupinf.get("countryname")) +
                DataTools.convertToStr(objmovesupinf.get("townname")) +
                DataTools.convertToStr(objmovesupinf.get("townname")) +
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdmc")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdmc")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmovesupinf.get
                        ("obj_movesup_azfs"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmovesupinf.get
                        ("obj_movesup_fwlx"))),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azfwjzmj")),
                id,
                DataTools.convertToStr(source.get("provincename")) +
                        DataTools.convertToStr(source.get("cityname")) +
                        DataTools.convertToStr(source.get("countryname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("obj_reloca_jtyzz")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get
                        ("obj_reloca_yfwjg"))),
                DataTools.convertToStr(source.get("obj_movesup_ttjzjdmj")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_jzhj")
                )), DataTools.convertToStr(source.get("obj_reloca_fwrjjzmj")),
                DataTools.convertToStr(source.get("obj_reloca_yfwjzmj")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_ttjzjdmj")),
                DataTools.subDateStr(DataTools.convertToStr(objmovesupinf.get("obj_movesup_ttjzjdsj"))),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_ttjzjjhbzzj")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_rjjzmj")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_jgfcb")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_jgfbzzj")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_zcje")),
                DataTools.subDateStr(DataTools.convertToStr(objmovesupinf.get("obj_movesup_jysj"))),
                DataTools.subDateStr(DataTools.convertToStr(objmovesupinf.get("obj_movesup_sjrzsj")))
        );

        //脱贫措施
        MeasuresInfoVo measuresInfoVo = new MeasuresInfoVo(
                DataTools.convertToStr(objmeasuresinfo.get("obj_measures_bqhjtjyrs")),
                DataTools.convertToStr(objmeasuresinfo.get("obj_measures_bqhjtnsr")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_bqhsrly"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_cyfccs"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_hxtpcs"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_qttpcs"))),
                DataTools.convertToStr(objmeasuresinfo.get("obj_measures_sftp")));

        //附件信息
        SearchRequestBuilder attachSearchB = esClientManager.getESClient().prepareSearch("obj_attach_inf").setTypes("attach_inf").setQuery
                (termQuery("obat_objectid.keyword", id));
        log.info("reqeust: " + attachSearchB.toString());
        SearchResponse attachSearchResponse = attachSearchB.execute().actionGet();
        log.info("response:" + attachSearchResponse.toString());

        List<AttachInfoVo> attachInfoVoList = new ArrayList<>();
        SearchHit[] searchHits = attachSearchResponse.getHits().getHits();
        AttachInfoVo huzhuAvatorInfoVo = null;
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();

            //由于业务库中附件名称存储字段不统一，所以户主照片需要单独处理
            String filePath = DataTools.convertToStr(searchHitSource.get("obat_localpath")) +
                    DataTools.convertToStr(searchHitSource.get("obat_serverpath"));
            if (StringUtils.equalsIgnoreCase(DataTools.convertToStr(searchHitSource.get("obat_datasourcetype")), "1")) {
                filePath += DataTools.convertToStr(searchHitSource.get("obat_attachname"));
                huzhuAvatorInfoVo = new AttachInfoVo(DataTools.convertToStr(searchHitSource.get("obat_attachsize")),
                        filePath,
                        DataTools.convertToStr(searchHitSource.get("obat_sourcename")),
                        DataTools.subDateStr(DataTools.convertToStr(searchHitSource.get("obat_uploadtime"))));
            } else {
                filePath += DataTools.convertToStr(searchHitSource.get("obat_localname"));
                AttachInfoVo attachInfoVo = new AttachInfoVo(DataTools.convertToStr(searchHitSource.get("obat_attachsize")),
                        filePath,
                        DataTools.convertToStr(searchHitSource.get("obat_sourcename")),
                        DataTools.subDateStr(DataTools.convertToStr(searchHitSource.get("obat_uploadtime"))));
                attachInfoVoList.add(attachInfoVo);
            }
        }

        //帮扶措施
        SearchRequestBuilder suppeopleSearchB = esClientManager.getESClient().prepareSearch("obj_suppeople_info").setTypes("suppeople_info")
                .setQuery(matchPhraseQuery("relocationid", id));
        log.info("reqeust: " + suppeopleSearchB.toString());
        SearchResponse suppeopleSearchResponse = suppeopleSearchB.execute().actionGet();
        log.info("response:" + suppeopleSearchResponse.toString());

        List<SupportInfoVo> supportInfoVoList = new ArrayList<>();
        SearchHit[] suppeopleSearchHits = suppeopleSearchResponse.getHits().getHits();
        for (SearchHit searchHit : suppeopleSearchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();
            SupportInfoVo supportInfoVo = new SupportInfoVo(
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("obj_suppeople_bfcs"))),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_dwlsgx")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_lxdh")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_szdw")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_xb")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_xm")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_zwjb")),
                    DataTools.convertToStr(searchHitSource.get("sup_peopleid")));
            supportInfoVoList.add(supportInfoVo);
        }

        ObjMoveInfoVo objMoveInfoVo = new ObjMoveInfoVo();
        objMoveInfoVo.setAttachInfoList(attachInfoVoList);
        objMoveInfoVo.setFamilyMemberInfoList(familyMemberInfoVoList);
        objMoveInfoVo.setMeasuresInfo(measuresInfoVo);
        objMoveInfoVo.setMovesupInfo(movesupInfoVo);
        objMoveInfoVo.setObjBaseInfo(objBaseInfoVo);
        objMoveInfoVo.setSupportInfoList(supportInfoVoList);
        objMoveInfoVo.setHuzhuAvatorInfoVo(huzhuAvatorInfoVo);

        return new CommonResultData<>(HttpStatus.OK.value(), "suc", objMoveInfoVo);
    }

    @Override
    public CommonResultData<ObjMoveInfoVo> getPoorObjDetailInfoById(String id) throws YJHHException {
        //获取搬迁户基础表
        QueryBuilder idsQueryBuilder = QueryBuilders.idsQuery().addIds(id);
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setQuery
                (idsQueryBuilder);

        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());

        Map<String, JSONObject> deptInfoMap = initDataFactory.getDeptInfoMap();

        SearchHit[] hits = searchResponse.getHits().getHits();

        if (hits == null || hits.length <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }

        Map<String, Object> source = hits[0].getSource();

        Double jd = source.get("jd") == null ? null : Double.parseDouble(source.get("jd").toString());
        Double wd = source.get("wd") == null ? null : Double.parseDouble(source.get("wd").toString());
        String deptid = source.get("deptid").toString();

        JSONObject deptInfo = deptInfoMap.get(deptid);
        if (deptInfo != null && (jd == null || wd == null)) {
            String longitude = deptInfo.getString("longitude");
            jd = (StringUtils.isBlank(longitude) || StringUtils.equalsIgnoreCase("null", longitude)) ? null : Double.parseDouble(longitude);
            String latitude = deptInfo.getString("latitude");
            wd = (StringUtils.isBlank(latitude) || StringUtils.equalsIgnoreCase("null", latitude)) ? null : Double.parseDouble(latitude);
        }

        Map<String, Object> objmovesupinf = (Map<String, Object>) source.get("objmovesupinf");
        Map<String, Object> objmeasuresinfo = (Map<String, Object>) source.get("objmeasuresinfo");
        List<Map<String, Object>> objfamilyinfList = getFamilyMemberByObjId(id);

        //贫困户基础信息
        ObjBaseInfoVo objBaseInfoVo = new ObjBaseInfoVo(wd, jd,
                DataTools.convertToStr(source.get("provincename")) +
                        DataTools.convertToStr(source.get("cityname")) +
                        DataTools.convertToStr(source.get("countryname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("obj_reloca_jtyzz")),
                DataTools.convertToStr(source.get("obj_reloca_hzxm")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_jkzk"))),
                DataTools.convertToStr(source.get("obj_reloca_jtrk")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_ldnl"))),
                DataTools.convertToStr(source.get("obj_reloca_sfzh")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_whcd"))),
                DataTools.convertToStr(source.get("obj_reloca_xb")),
                DataTools.convertToStr(source.get("relocationid")),
                DataTools.convertToStr(source.get("removaltypename")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdid")),
                StringUtils.isBlank(DataTools.convertToStr(objmovesupinf.get("pointy"))) ? 0.0 : Double
                        .parseDouble
                                (DataTools.convertToStr(objmovesupinf.get("pointy"))),
                StringUtils.isBlank(DataTools.convertToStr(objmovesupinf.get("pointx"))) ? 0.0 : Double
                        .parseDouble
                                (DataTools.convertToStr(objmovesupinf.get("pointx"))),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdmc")),
                DataTools.convertToStr(source.get("obj_reloca_lxdh")),
                DataTools.convertToStr(source.get("obj_reloca_hjbh")));

        Map<String, Object> objHzMap = new HashMap<>();
        //家庭成员信息
        List<FamilyMemberInfoVo> familyMemberInfoVoList = new ArrayList<>();
        for (Map<String, Object> objfamilyinfMap : objfamilyinfList) {
            FamilyMemberInfoVo familyMemberInfoVo = new FamilyMemberInfoVo(DataTools.convertToStr(objfamilyinfMap.get("familymemberid")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr
                            (objfamilyinfMap.get
                                    ("obj_relfamily_jkzk"))),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr
                            (objfamilyinfMap.get
                                    ("obj_relfamily_ldnl"))),
                    DataTools.convertToStr(objfamilyinfMap.get("obj_relfamily_name")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr
                            (objfamilyinfMap.get
                                    ("obj_relfamily_whcd"))),
                    DataTools.convertToStr(objfamilyinfMap.get("obj_relfamily_yhzgx")),
                    id,
                    DataTools.convertToStr(objfamilyinfMap.get("obj_relfamily_xb"))
            );

            if (StringUtils.equalsIgnoreCase(objBaseInfoVo.getOBJ_RELOCA_SFZH(), DataTools.convertToStr(objfamilyinfMap.get("obj_relfamily_sfzh")))) {
                objHzMap = objfamilyinfMap;
            }
            familyMemberInfoVoList.add(familyMemberInfoVo);
        }

        objBaseInfoVo.setOBJ_RELOCA_XB(DataTools.convertToStr(objHzMap.get("obj_relfamily_xb")));
        objBaseInfoVo.setOBJ_RELOCA_YHYDBH(DataTools.convertToStr(objHzMap.get("obj_reloca_yhydbh")));
        objBaseInfoVo.setOBJ_RELOCA_WHCD(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_whcd"))));
        objBaseInfoVo.setOBJ_RELOCA_LDNL(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_ldnl"))));
        objBaseInfoVo.setOBJ_RELOCA_JKZK(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_jkzk"))));

        //搬迁信息
        MovesupInfoVo movesupInfoVo = new MovesupInfoVo(DataTools.convertToStr(objmovesupinf.get("provincename")) +
                DataTools.convertToStr(objmovesupinf.get("cityname")) +
                DataTools.convertToStr(objmovesupinf.get("countryname")) +
                DataTools.convertToStr(objmovesupinf.get("townname")) +
                DataTools.convertToStr(objmovesupinf.get("townname")) +
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdmc")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdmc")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmovesupinf.get
                        ("obj_movesup_azfs"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmovesupinf.get
                        ("obj_movesup_fwlx"))),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azfwjzmj")),
                id,
                DataTools.convertToStr(source.get("provincename")) +
                        DataTools.convertToStr(source.get("cityname")) +
                        DataTools.convertToStr(source.get("countryname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("obj_reloca_jtyzz")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get
                        ("obj_reloca_yfwjg"))),
                DataTools.convertToStr(source.get("obj_movesup_ttjzjdmj")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_jzhj")
                )), DataTools.convertToStr(source.get("obj_reloca_fwrjjzmj")),
                DataTools.convertToStr(source.get("obj_reloca_yfwjzmj")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_ttjzjdmj")),
                DataTools.subDateStr(DataTools.convertToStr(objmovesupinf.get("obj_movesup_ttjzjdsj"))),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_ttjzjjhbzzj")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_rjjzmj")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_jgfcb")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_jgfbzzj")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_zcje")),
                DataTools.subDateStr(DataTools.convertToStr(objmovesupinf.get("obj_movesup_jysj"))),
                DataTools.subDateStr(DataTools.convertToStr(objmovesupinf.get("obj_movesup_sjrzsj"))));


        //脱贫措施
        MeasuresInfoVo measuresInfoVo = new MeasuresInfoVo(
                DataTools.convertToStr(objmeasuresinfo.get("obj_measures_bqhjtjyrs")),
                DataTools.convertToStr(objmeasuresinfo.get("obj_measures_bqhjtnsr")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_bqhsrly"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_cyfccs"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_hxtpcs"))),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_qttpcs"))),
                DataTools.convertToStr(objmeasuresinfo.get("obj_measures_sftp")));

        //附件信息
        SearchRequestBuilder attachSearchB = esClientManager.getESClient().prepareSearch("obj_attach_inf").setTypes("attach_inf").setQuery
                (termQuery("obat_objectid.keyword", id));
        log.info("reqeust: " + attachSearchB.toString());
        SearchResponse attachSearchResponse = attachSearchB.execute().actionGet();
        log.info("response:" + attachSearchResponse.toString());

        List<AttachInfoVo> attachInfoVoList = new ArrayList<>();
        SearchHit[] searchHits = attachSearchResponse.getHits().getHits();
        AttachInfoVo huzhuAvatorInfoVo = null;
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();

            //由于业务库中附件名称存储字段不统一，所以户主照片需要单独处理
            String filePath = DataTools.convertToStr(searchHitSource.get("obat_localpath")) +
                    DataTools.convertToStr(searchHitSource.get("obat_serverpath"));
            if (StringUtils.equalsIgnoreCase(DataTools.convertToStr(searchHitSource.get("obat_datasourcetype")), "1")) {
                filePath += DataTools.convertToStr(searchHitSource.get("obat_attachname"));
                huzhuAvatorInfoVo = new AttachInfoVo(DataTools.convertToStr(searchHitSource.get("obat_attachsize")),
                        filePath,
                        DataTools.convertToStr(searchHitSource.get("obat_sourcename")),
                        DataTools.subDateStr(DataTools.convertToStr(searchHitSource.get("obat_uploadtime"))));
            } else {
                filePath += DataTools.convertToStr(searchHitSource.get("obat_localname"));
                AttachInfoVo attachInfoVo = new AttachInfoVo(DataTools.convertToStr(searchHitSource.get("obat_attachsize")),
                        filePath,
                        DataTools.convertToStr(searchHitSource.get("obat_sourcename")),
                        DataTools.subDateStr(DataTools.convertToStr(searchHitSource.get("obat_uploadtime"))));
                attachInfoVoList.add(attachInfoVo);
            }
        }

        //帮扶措施
        SearchRequestBuilder suppeopleSearchB = esClientManager.getESClient().prepareSearch("obj_suppeople_info").setTypes("suppeople_info")
                .setQuery(matchPhraseQuery("relocationid", id));
        log.info("reqeust: " + suppeopleSearchB.toString());
        SearchResponse suppeopleSearchResponse = suppeopleSearchB.execute().actionGet();
        log.info("response:" + suppeopleSearchResponse.toString());

        List<SupportInfoVo> supportInfoVoList = new ArrayList<>();
        SearchHit[] suppeopleSearchHits = suppeopleSearchResponse.getHits().getHits();
        for (SearchHit searchHit : suppeopleSearchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();
            SupportInfoVo supportInfoVo = new SupportInfoVo(
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("obj_suppeople_bfcs"))),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_dwlsgx")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_lxdh")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_szdw")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_xb")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_xm")),
                    DataTools.convertToStr(searchHitSource.get("obj_suppeople_zwjb")),
                    DataTools.convertToStr(searchHitSource.get("sup_peopleid")));
            supportInfoVoList.add(supportInfoVo);
        }
        
        /*搬迁对象补充信息*/
        /* 就业*/
        DecimalFormat df = new DecimalFormat("######0.00");

        //搬迁前人均年收入
        String jtnsr = DataTools.convertToStr(source.get("obj_reloca_jtnsr"));
        Double nsr = XaUtil.isEmpty(jtnsr) ? 0 : Double.parseDouble(jtnsr);
        String rk = DataTools.convertToStr(source.get("familyMemberCount"));
        Double rjNsr = nsr / Integer.parseInt(rk);

        //搬迁后人均收入
        String jtnsrAfter = DataTools.convertToStr(objmeasuresinfo.get("obj_measures_bqhjtnsr"));
        Double nsrAfter = XaUtil.isEmpty(jtnsrAfter) ? 0 : Double.parseDouble(jtnsrAfter);
        Double rjNsrAfter = nsr + nsrAfter;

        EmploymentInfoVo employmentInfoVo = new EmploymentInfoVo(
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_ldnl"))),
                DataTools.convertToStr(source.get("obj_reloca_ldlrs")),
                "", commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_jtzysrly"))),
                jtnsr + "", commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_ldnl"))),
                DataTools.convertToStr(source.get("obj_reloca_ldlrs")),
                DataTools.convertToStr(objmeasuresinfo.get("obj_measures_bqhjtjyrs")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_bqhsrly"))),
                rjNsrAfter + ""

        );

        /*脱贫*/
        BoolQueryBuilder relocationQuery = boolQuery().must(termQuery("relocationid.keyword", id));

        searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_peoplelist_inf").setTypes("peoplelist_inf").setQuery
                (relocationQuery);

        log.info("reqeust: " + searchRequestBuilder.toString());
        searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());

        SearchHit[] peopleSearchHits = searchResponse.getHits().getHits();

        OutOfPovertyInfoVo outOfPovertyInfoVo = new OutOfPovertyInfoVo();

        for (SearchHit searchHit : peopleSearchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();

            outOfPovertyInfoVo.setMainCausesOfPoverty(commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get
                    ("obj_peoplelist_zyzpyy"))));
            outOfPovertyInfoVo.setPovertyProperty(commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get
                    ("obj_peoplelist_pkhsx"))));
        }

        outOfPovertyInfoVo.setPovertyAlleviationMeasures(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get
                ("obj_measures_hxtpcs"))));

        outOfPovertyInfoVo.setOtherMeasures(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objmeasuresinfo.get
                ("obj_measures_qttpcs"))));  //其他措施

        outOfPovertyInfoVo.setWhetherToEscapePoverty(DataTools.convertToStr(objmeasuresinfo.get("obj_measures_sftp")));  //是否脱贫

        outOfPovertyInfoVo.setPovertyAlleviationTime(DataTools.subDateStr(DataTools.convertToStr(objmeasuresinfo.get
                ("obj_measures_tpxhsj"))));
        //脱贫时间


        //生活环境信息
        LifeInfoVo lifeInfoVo = new LifeInfoVo();
        lifeInfoVo.setEnvironment(commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get("obj_reloca_jzhj"))));    //居住环境

        //教育信息
        EducationInfoVo educationInfoVo = new EducationInfoVo();
        educationInfoVo.setDegreeOfCulture(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_whcd")))); //文化程度
        educationInfoVo.setDegreeOfCultureAfter(commonDataComponent.getSysDicValueById(DataTools.convertToStr(objHzMap.get("obj_relfamily_whcd"))));

        //医疗信息
        MedicalTreatmentInfoVo medicalTreatmentInfoVo = new MedicalTreatmentInfoVo();

        /*安置点规划信息查询*/
        String azdId = DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdid"));
        if (!XaUtil.isEmpty(azdId)) {

            BoolQueryBuilder azdQuery = boolQuery().must(termQuery("pointid.keyword", azdId));
            azdQuery.must(termQuery("stype", "0"));
            searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_pointprograming_inf").setTypes("pointprograming_inf").setQuery
                    (azdQuery);

            log.info("reqeust: " + searchRequestBuilder.toString());
            searchResponse = searchRequestBuilder.execute().actionGet();
            log.info("response:" + searchResponse.toString());

            SearchHit[] azdSearchHits = searchResponse.getHits().getHits();

            for (SearchHit searchHit : azdSearchHits) {
                Map<String, Object> searchHitSource = searchHit.getSource();
                //生活信息 搬迁后活动室数量
                lifeInfoVo.setActivityRoomAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_hdsgs")));
                //生活信息 搬迁后环卫设施
                lifeInfoVo.setSanitationAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_hwsscd")));

                //教育信息 搬迁后周边学校数量
                educationInfoVo.setSchoolAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_xxgs")));

                //搬迁后周边学校个数
                educationInfoVo.setSchoolCountAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_xxgs")));

                //搬迁后周边学校面积
                educationInfoVo.setSchoolAreaAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_xxcd")));

                //搬迁后周边幼儿园个数
                educationInfoVo.setKindergartenCountAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_yrygs")));

                //搬迁后周边幼儿园面积
                educationInfoVo.setKindergartenAreaAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_yrycd")));

                //医疗信息 搬迁后医院数量
                medicalTreatmentInfoVo.setHospitalQuantityAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_wsysgs")));

                //输水管道
                lifeInfoVo.setSsgdcdAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_ssgdcd")));

                //输电线路
                lifeInfoVo.setSdxlcdAfter(DataTools.convertToStr(searchHitSource.get("point_contruction_sdxlcd")));
            }

        }

        ObjMoveInfoVo objMoveInfoVo = new ObjMoveInfoVo();
        objMoveInfoVo.setAttachInfoList(attachInfoVoList);
        objMoveInfoVo.setFamilyMemberInfoList(familyMemberInfoVoList);
        objMoveInfoVo.setMeasuresInfo(measuresInfoVo);
        objMoveInfoVo.setMovesupInfo(movesupInfoVo);
        objMoveInfoVo.setObjBaseInfo(objBaseInfoVo);
        objMoveInfoVo.setSupportInfoList(supportInfoVoList);
        objMoveInfoVo.setHuzhuAvatorInfoVo(huzhuAvatorInfoVo);

        objMoveInfoVo.setEmploymentInfoVo(employmentInfoVo); //就业信息
        objMoveInfoVo.setOutOfPovertyInfoVo(outOfPovertyInfoVo); //脱贫信息

        objMoveInfoVo.setEducationInfoVo(educationInfoVo); //教育信息
        objMoveInfoVo.setMedicalTreatmentInfoVo(medicalTreatmentInfoVo); //医疗信息

        //获取安置点信息
        String placementPointId = DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdid"));   //安置点ID
        if (StringUtils.isNotBlank(placementPointId)) {
            //获取安置点简单信息
            idsQueryBuilder = QueryBuilders.idsQuery().addIds(placementPointId);
            searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_placementpoint_inf").setTypes
                    ("placementpoint_inf").setQuery(idsQueryBuilder);

            log.info("reqeust: " + searchRequestBuilder.toString());
            searchResponse = searchRequestBuilder.execute().actionGet();
            log.info("response:" + searchResponse.toString());

            hits = searchResponse.getHits().getHits();
            if (hits == null || hits.length <= 0) {
                new CommonResultData<>(HttpStatus.OK.value(), "suc", null);
            }

            Map<String, Object> searchHitSource = hits[0].getSource();

            //生活信息 搬迁后居住环境
            lifeInfoVo.setEnvironmentAfter(commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_seladdress"))));
            //居住环境

            //安置点基本信息--------------------------------------------------------------------
            PlacementPointBaseInfoVo placementPointBaseInfoVo = new PlacementPointBaseInfoVo(
                    DataTools.convertToStr(searchHitSource.get("a_allareas"), "亩"),
                    DataTools.convertToStr(searchHitSource.get("a_constructioncycle")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_demostate"))),
                    DataTools.subDateStr(DataTools.convertToStr(searchHitSource.get("a_endprojecttime"))),
                    DataTools.convertToStr(searchHitSource.get("a_firstyear")),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_housetype"))),
                    StringUtils.equalsIgnoreCase("1", DataTools.convertToStr(searchHitSource.get("a_isincity"))) ? "是" : "否",
                    DataTools.convertToStr(searchHitSource.get("a_pointaddress")),
                    placementPointId,
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_pointtype"))),
                    StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("a_pointx"))) ? 0.0 : Double
                            .parseDouble
                                    (DataTools.convertToStr(searchHitSource.get("a_pointx"))),
                    StringUtils.isBlank(DataTools.convertToStr(searchHitSource.get("a_pointy"))) ? 0.0 : Double
                            .parseDouble
                                    (DataTools.convertToStr(searchHitSource.get("a_pointy"))),
                    DataTools.convertToStr(searchHitSource.get("a_projname")),
                    DataTools.subDateStr(DataTools.convertToStr(searchHitSource.get("a_recordtime"))),
                    commonDataComponent.getSysDicValueById(DataTools.convertToStr(searchHitSource.get("a_seladdress"))),
                    DataTools.subDateStr(DataTools.convertToStr(searchHitSource.get("a_startprojecttime"))),
                    DataTools.convertToStr(searchHitSource.get("a_usercname")));
            objMoveInfoVo.setPlacementPointBaseInfoVo(placementPointBaseInfoVo);
        }

        objMoveInfoVo.setLifeInfoVo(lifeInfoVo); //生活信息

        return new CommonResultData<>(HttpStatus.OK.value(), "suc", objMoveInfoVo);
    }

    @Override
    public CommonResultData<ObjMoveInStatisticsVo> getObjMoveInStatisticsByAreaCodeAndMoveType(String areaCode, String moveType) throws
            YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        List<DeptBean> subDept = commonDataComponent.getSubDeptByDeptId(sysDeptInfo.getDeptID());

        int subDeptSize = subDept.size();
        if (subDept == null || subDeptSize <= 0 || !DataConsts.getMoveTypeMap().containsKey(moveType)) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        //提取子部门ID为数组
        List<String> areaList = new ArrayList();
        List<String> deptIds = new ArrayList<>();
        for (DeptBean deptBean : subDept) {
            deptIds.add(deptBean.getDeptID());
            areaList.add(deptBean.getDeptName());
        }

        //获取按区域分不同类型的搬迁户数
        long[] areaHSList = getAreaTotalHSArea(areaList, subDeptSize, deptIds, moveType);

        //查询每个区域按年入住户数------------------------------------------
        Map<String, long[]> yearRZMap = queryAreaRZByYear(sysDeptInfo, areaList, subDeptSize, moveType);
        if (yearRZMap == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }

        List<String> yearSet = new ArrayList<>(yearRZMap.keySet());
        Collections.sort(yearSet);   //按年从小到大排序

        //按年，入住户数，转化返回的数据格式
        List<List<Long>> yearMoveInList = new ArrayList<>();
        List<String> titleList = new ArrayList();
        titleList.add(DataConsts.getMoveTypeMap().get(moveType));
        for (String year : yearSet) {
            long[] longs = yearRZMap.get(year);
            ArrayList<Long> areaHSs = Lists.newArrayList();
            for (long areaHS : longs) {
                areaHSs.add(areaHS);
            }
            yearMoveInList.add(areaHSs);
            titleList.add(year + "入住");
        }

        //转化数据格式
        ArrayList<Long> areaHSs = Lists.newArrayList();
        for (long areaHS : areaHSList) {
            areaHSs.add(areaHS);
        }

        return new CommonResultData<>(HttpStatus.OK.value(), "no data", new ObjMoveInStatisticsVo(areaHSs, areaList, titleList,
                yearMoveInList));
    }

    @Override
    public CommonResultData<ObjMoveInStatisticsVo> getObjMoveInStatisticsByAreaCodeAndMoveTypeReport(String areaCode, String moveType) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        List<DeptBean> subDept = commonDataComponent.getSubDeptByDeptId(sysDeptInfo.getDeptID());

        int subDeptSize = subDept.size();
        if (subDept == null || subDeptSize <= 0 || !DataConsts.getMoveTypeMap().containsKey(moveType)) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }

        //获取最大上报年月
        MaxYearMonth maxReportYearMonth = commonDataComponent.getMaxReportYearMonth(null);

        if (maxReportYearMonth == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }

        List<String> areaList = new ArrayList();

        List<String> titleList = new ArrayList();
        titleList.add(DataConsts.getMoveTypeMap().get(moveType));
        for (int year = taskStartYear; year <= taskEndYear; year++) {
            titleList.add(year + "入住");
        }

        List<List<Long>> yearMoveInList = new ArrayList<>();

        List<Long> totalHSList = new ArrayList<>();
        for (int i = 0; i < subDept.size(); i++) {
            areaList.add(subDept.get(i).getDeptName());
            totalHSList.add(0L);
        }
        for (int year = taskStartYear; year <= taskEndYear; year++) {
            //按年进行查询
            List<Long> yearMoveInHSListTemp = new ArrayList<>();
            for (int i = 0; i < subDept.size(); i++) {
                //如果统计年份大于当前年份则直接用0
                if (year > Integer.parseInt(maxReportYearMonth.getYear())) {
                    yearMoveInHSListTemp.add(0L);
                    continue;
                }

                SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_imppr_targetdata").setTypes("imppr_targetdata")
                        .setSize(1);
                BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("deptid.keyword", subDept.get(i).getDeptID()));
                if (StringUtils.equalsIgnoreCase(DataConsts.RemoveType.YDFP, moveType)) {
                    boolQueryBuilder.must(termQuery("imptype", DataConsts.ReportRemoveType.YDFP));
                } else if (StringUtils.equalsIgnoreCase(DataConsts.RemoveType.BZ, moveType)) {
                    boolQueryBuilder.must(termQuery("imptype", DataConsts.ReportRemoveType.BZST));
                } else {
                    boolQueryBuilder.must(termQuery("imptype", DataConsts.ReportRemoveType.ALL));
                }

                boolQueryBuilder.must(termQuery("fillyear", year));
                //如果是当前年则取当前年最大的统计月份
                boolQueryBuilder.must(termQuery("fillmonth", StringUtils.equalsIgnoreCase(maxReportYearMonth.getYear(), year + "") ? maxReportYearMonth.getMonth() : "12"));
                searchRequestBuilder.setQuery(boolQueryBuilder);

                log.info("request=" + searchRequestBuilder.toString());
                SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
                log.info("response=" + searchResponse.toString());

                SearchHit[] searchHits = searchResponse.getHits().getHits();

                if (searchHits == null || searchHits.length <= 0) {
                    yearMoveInHSListTemp.add(0L);
                    continue;
                }
                Map<String, Object> source = searchHits[0].getSource();
                Long rzHs = DataTools.convertToLone(source.get("rz_hs"));
                yearMoveInHSListTemp.add(rzHs);

                Long taskHs = DataTools.convertToLone(source.get("task_hs"));
                Long deptTotalHS = totalHSList.get(i);
                if ((taskHs == null ? 0 : taskHs.longValue()) > deptTotalHS.longValue()) {
                    totalHSList.set(i, taskHs);
                }
            }

            yearMoveInList.add(yearMoveInHSListTemp);
        }

        //调整数据结构
        /*List<List<Long>> yearMoveInListNew = new ArrayList<>();
        yearMoveInListNew.add(totalHSList);
        yearMoveInListNew.addAll(yearMoveInList);*/

        return new CommonResultData<>(HttpStatus.OK.value(), "no data", new ObjMoveInStatisticsVo(totalHSList, areaList, titleList,
                yearMoveInList));
    }

    @Override
    public CommonResultData<List<ObjZPYYVo>> getObjPoorTypeStatisticsByAreaCode(String areaCode) throws YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        //PrefixQueryBuilder areacodequery = prefixQuery("deptno", sy_dept_info.getDeptno());
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize
                (0).setQuery
                (areacodequery);
        TermsAggregationBuilder deptsAgg = AggregationBuilders.terms("depts").field("obj_reloca_zypkyy.keyword").missing(DataConsts.UNKNOWN)
                .size(10000);

        searchRequestBuilder.addAggregation(deptsAgg);

        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());

        List<Aggregation> aggregations = searchResponse.getAggregations().asList();

        if (aggregations == null || aggregations.size() <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        StringTerms stringTerms = (StringTerms) aggregations.get(0);

        Map<String, Long> poorTypeCountMap = new HashMap<>();
        for (StringTerms.Bucket bucket : stringTerms.getBuckets()) {
            String poorTypes = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();

            String[] types = StringUtils.split(poorTypes, ",");
            for (String poorType : types) {
                if (poorTypeCountMap.containsKey(poorType)) {
                    poorTypeCountMap.put(poorType, (poorTypeCountMap.get(poorType) + docCount));
                } else {
                    poorTypeCountMap.put(poorType, docCount);
                }
            }
        }

        //转化数据字典值，并对结果进行排序
        List<ObjZPYYVo> objZPYYVos = new ArrayList<>();
        for (Map.Entry<String, Long> entry : poorTypeCountMap.entrySet()) {
            String poorTypeId = entry.getKey();
            if (StringUtils.equalsIgnoreCase(DataConsts.UNKNOWN, poorTypeId)) {
                continue;
            }
            Long poorObjCount = entry.getValue();
            String poorTypeName = commonDataComponent.getSysDicValueById(poorTypeId);
            objZPYYVos.add(new ObjZPYYVo(poorObjCount, poorTypeId, poorTypeName));
        }

        //排序
        Collections.sort(objZPYYVos, (ObjZPYYVo o1, ObjZPYYVo o2) -> {
            return o2.getPoorObjCount() <= o1.getPoorObjCount() ? -1 : 1;
        });

        return new CommonResultData<>(HttpStatus.OK.value(), "no data", objZPYYVos);
    }

    /**
     * 获取按区域分不同类型的搬迁户数。
     *
     * @param areaList    区域名称集合
     * @param subDeptSize 子部门个数
     * @param deptIds     部门id集合
     * @param moveType    搬迁类型
     * @return
     */
    private long[] getAreaTotalHSArea(List<String> areaList, int subDeptSize, List<String> deptIds, String moveType) {
        long[] areaHSList = new long[subDeptSize];

        //获取总的计划搬迁人数-----------------------
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("deletestate", "0"));
        areacodequery.must(termQuery("stype", "1"));
        areacodequery.must(termsQuery("deptid.keyword", deptIds));
        areacodequery.filter(existsQuery("deptname.keyword"));

        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_pointprograming_inf").setTypes
                ("pointprograming_inf");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(new String[]{"deptid", "deptname", "point_placement_qzjdlipkhs",
                "point_placement_bzhs", "point_placement_sths", "point_placement_allhs"}, null);
        searchSourceBuilder.query(areacodequery);
        FieldSortBuilder sort = new FieldSortBuilder("deptno.keyword");
        searchSourceBuilder.sort(sort);
        searchSourceBuilder.size(10000);
        searchRequestBuilder.setSource(searchSourceBuilder);

        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());

        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit searchHit : hits) {
            Map<String, Object> searchHitSource = searchHit.getSource();
            Long hs = 0L;
            switch (moveType) {
                case DataConsts.RemoveType.YDFP:
                    hs = (long) (DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_qzjdlipkhs"))));
                    break;
                case DataConsts.RemoveType.BZ:
                    hs = (long) DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_bzhs")))
                            + (long) DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_sths")));
                    break;
                default:
                    hs = (long) DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_allhs")));
                    break;
            }
            areaHSList[areaList.indexOf(searchHitSource.get("deptname"))] = hs;
        }
        return areaHSList;
    }

    /**
     * 查询每个区域按年入住户数
     *
     * @param sysDeptInfo 部门对象
     * @param areaList    区域名称集合
     * @param subDeptSize 子部门个数
     * @param moveType    搬迁类型
     * @return
     */
    private Map<String, long[]> queryAreaRZByYear(DeptBean sysDeptInfo, List<String> areaList, int subDeptSize, String moveType) {
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("isdelete", "0"));
        areacodequery.must(prefixQuery("deptno.keyword", sysDeptInfo.getDeptno()));
        areacodequery.must(termQuery("objmovesupinf.obj_movesup_state", "1"));

        if (StringUtils.equalsIgnoreCase(DataConsts.RemoveType.YDFP, moveType)) {
            areacodequery.must(termsQuery("removaltypeid", "1"));
        } else if (StringUtils.equalsIgnoreCase(DataConsts.RemoveType.BZ, moveType)) {
            areacodequery.must(termsQuery("removaltypeid", "2", "3"));
        } else if (StringUtils.equalsIgnoreCase(DataConsts.RemoveType.ST, moveType)) {
            areacodequery.must(termsQuery("removaltypeid", "2", "3"));
        }
        //查询2015年到当前世间的年统计
        areacodequery.must(rangeQuery("objmovesupinf.obj_movesup_sjrzsj").format("yyyy-MM-dd").gt("2015-12-31").lt(DateUtils.formatDate(new Date(),
                "yyyy-MM-dd")));
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setSize
                (0).setQuery(areacodequery);
        TermsAggregationBuilder deptsAgg = AggregationBuilders.terms("depts").field(DataConsts.getDeptName(sysDeptInfo.getDeptLevel() + 1))
                .missing(DataConsts.UNKNOWN)
                .size(100);

        //入住状态
        DateHistogramAggregationBuilder moveUpStatus = AggregationBuilders.dateHistogram("yearGroup").field("objmovesupinf.obj_movesup_sjrzsj")
                .format("yyyy").dateHistogramInterval(DateHistogramInterval.YEAR);
        deptsAgg.subAggregation(moveUpStatus);

        searchRequestBuilder.addAggregation(deptsAgg);

        log.info("reqeust: " + searchRequestBuilder.toString());

        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());

        List<Aggregation> aggregations = searchResponse.getAggregations().asList();

        if (aggregations == null || aggregations.size() <= 0) {
            return null;
        }

        Map<String, long[]> yearRZMap = new HashMap<>();

        StringTerms stringTerms = (StringTerms) aggregations.get(0);
        for (StringTerms.Bucket bucket : stringTerms.getBuckets()) {
            String deptName = bucket.getKeyAsString();
            InternalDateHistogram internalDateHistogram = (InternalDateHistogram) bucket.getAggregations().asList().get(0);
            for (InternalDateHistogram.Bucket ruzhuTermBucket : internalDateHistogram.getBuckets()) {
                String yearLabel = ruzhuTermBucket.getKeyAsString();   //已入住户数
                long rzHS = ruzhuTermBucket.getDocCount();
                log.info(deptName + "  " + yearLabel + "年入住" + rzHS);
                long[] yearRZList = null;
                if (yearRZMap.containsKey(yearLabel)) {
                    yearRZList = yearRZMap.get(yearLabel);
                } else {
                    yearRZList = new long[subDeptSize];
                    yearRZMap.put(yearLabel, yearRZList);
                }
                yearRZList[areaList.indexOf(deptName)] = rzHS;
                yearRZMap.put(yearLabel, yearRZList);
            }
        }
        return yearRZMap;
    }

    private List<ObjRelocaSimpleInfoVo> prasePoorObjReps(String areaCode, DeptBean syDeptInfo, SearchResponse searchResponse, Map<String,
            JSONObject> deptInfoMap) {
        List<ObjRelocaSimpleInfoVo> list = new ArrayList<>();

        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> source = searchHit.getSource();
            String relocationid = source.get("relocationid").toString();

            Object obj_reloca_jtrk = source.get("obj_reloca_jtrk");
            if (obj_reloca_jtrk == null || StringUtils.isBlank(obj_reloca_jtrk.toString())) {
                obj_reloca_jtrk = source.get("familyMemberCount");
                if (obj_reloca_jtrk == null) {
                    obj_reloca_jtrk = "1";
                }
            }
            String familyMemberCount = obj_reloca_jtrk.toString();

            String householderName = source.get("obj_reloca_hzxm").toString();
            String moveType = source.get("removaltypename").toString();
            Double jd = source.get("jd") == null ? null : Double.parseDouble(source.get("jd").toString());
            Double wd = source.get("wd") == null ? null : Double.parseDouble(source.get("wd").toString());
            String deptid = source.get("deptid").toString();

            JSONObject deptInfo = deptInfoMap.get(deptid);
            String areaName = null;        //区域名称
            String arealevel = null;     //区域级别
            if (deptInfo != null) {
                areaName = deptInfo.getString("deptname");
                arealevel = deptInfo.getString("arealevel");
                if (jd == null || wd == null) {
                    String longitude = deptInfo.getString("longitude");
                    jd = (StringUtils.isBlank(longitude) || StringUtils.equalsIgnoreCase("null", longitude)) ? null : Double.parseDouble(longitude);
                    String latitude = deptInfo.getString("latitude");
                    wd = (StringUtils.isBlank(latitude) || StringUtils.equalsIgnoreCase("null", latitude)) ? null : Double.parseDouble(latitude);
                }
            }

            list.add(new ObjRelocaSimpleInfoVo(areaCode, arealevel, areaName,
                    familyMemberCount, householderName, relocationid, jd,
                    moveType, areaCode, syDeptInfo.getAreaLevel(),
                    syDeptInfo.getDeptName(), wd));
        }
        return list;
    }

    /**
     * 根据ES返回的结果解析移民搬迁的数据
     *
     * @param jsonStr es返回的数据
     * @return
     */
    private List<MoveDataVo> parseMoveTopData(String parentDeptID, String jsonStr, String parentAreaCode, String parentAreaName, String parentAreaLevel) {
        List<MoveDataVo> deptInfoVoListTemp = new ArrayList<>();

        Map<String, JSONObject> deptInfoMap = initDataFactory.getDeptInfoMap();

        JSONObject rootJsonObject = JSONObject.fromObject(jsonStr);
        JSONObject aggregations = rootJsonObject.getJSONObject("aggregations");
        JSONObject depts = aggregations.getJSONObject("depts");
        JSONArray buckets = depts.getJSONArray("buckets");

        int ydfpNumhushu = 0;
        int ydfpNumrenshu = 0;
        int bzstNumhushu = 0;
        int bzstNumrenshu = 0;

        for (int i = 0; i < buckets.size(); i++) {
            JSONObject bucket = (JSONObject) buckets.get(i);
            String deptId = bucket.getString("key");
            if (StringUtils.equalsIgnoreCase(deptId, DataConsts.UNKNOWN)) {
                continue;
            }

            MoveDataVo deptInfoVo = new MoveDataVo();
            deptInfoVo.setDeptId(deptId);
            deptInfoVo.setParentCode(parentAreaCode);
            deptInfoVo.setParentName(parentAreaName);
            deptInfoVo.setParentLevel(parentAreaLevel);


            if (deptInfoMap.containsKey(deptId)) {
                JSONObject jsonObject = deptInfoMap.get(deptId);
                deptInfoVo.setAreaName(jsonObject.getString("deptname"));
                deptInfoVo.setAreaCode(jsonObject.getString("areacode"));
                deptInfoVo.setAreaLevel(jsonObject.getString("arealevel"));
            }

            JSONObject removeTypeJsonObject = bucket.getJSONObject("removaltype");
            JSONArray removeTypeBuckets = removeTypeJsonObject.getJSONArray("buckets");
            for (int j = 0; j < removeTypeBuckets.size(); j++) {
                JSONObject removeTypeBucket = (JSONObject) removeTypeBuckets.get(j);
                String typeId = removeTypeBucket.getString("key");

                if (StringUtils.equalsIgnoreCase(typeId, DataConsts.UNKNOWN)) {
                    continue;
                }
                JSONObject peopleCountObje = removeTypeBucket.getJSONObject("peoples");
                int familyCount = removeTypeBucket.getInt("doc_count");
                int peopleCount = peopleCountObje.getInt("value");


                if (StringUtils.equalsIgnoreCase(DataConsts.RemoveType.YDFP, typeId)) {
                    deptInfoVo.setYdfpNumhushu(familyCount);
                    deptInfoVo.setYdfpNumrenshu(peopleCount);
                } else if (StringUtils.equalsIgnoreCase(DataConsts.RemoveType.BZ, typeId)
                        || StringUtils.equalsIgnoreCase(DataConsts.RemoveType.ST, typeId)) {
                    deptInfoVo.setBzstNumhushu(deptInfoVo.getBzstNumhushu() + familyCount);
                    deptInfoVo.setBzstNumrenshu(deptInfoVo.getBzstNumrenshu() + peopleCount);
                }

            }
            deptInfoVoListTemp.add(deptInfoVo);

            ydfpNumhushu += deptInfoVo.getYdfpNumhushu();
            ydfpNumrenshu += deptInfoVo.getYdfpNumrenshu();
            bzstNumhushu += deptInfoVo.getBzstNumhushu();
            bzstNumrenshu += deptInfoVo.getBzstNumrenshu();

        }

        List<MoveDataVo> deptInfoVoList = filterSortByAreaCode(parentDeptID, parentAreaCode, parentAreaName, parentAreaLevel, deptInfoVoListTemp);

        deptInfoVoList.add(new MoveDataVo("合计", bzstNumhushu, bzstNumrenshu, ydfpNumhushu, ydfpNumrenshu, "0"));

        return deptInfoVoList;
    }

    private List<MoveDataVo> filterSortByAreaCode(String parentDeptID, String parentAreaCode, String parentAreaName, String parentAreaLevel, List<MoveDataVo> deptInfoVoListTemp) {
        List<DeptBean> subDeptList = commonDataComponent.getSubDeptByDeptId(parentDeptID);
        List<MoveDataVo> deptInfoVoList = new ArrayList<>();
        for (DeptBean deptBean : subDeptList) {
            String subDeptId = deptBean.getDeptID();
            MoveDataVo moveDataVo = null;
            for (MoveDataVo moveDataVoTemp : deptInfoVoListTemp) {
                if (StringUtils.equalsIgnoreCase(subDeptId, moveDataVoTemp.getDeptId())) {
                    moveDataVo = moveDataVoTemp;
                }
            }
            if (moveDataVo == null) {
                moveDataVo = new MoveDataVo();
                moveDataVo.setDeptId(subDeptId);
                moveDataVo.setParentCode(parentAreaCode);
                moveDataVo.setParentName(parentAreaName);
                moveDataVo.setParentLevel(parentAreaLevel);

                moveDataVo.setAreaName(deptBean.getDeptName());
                moveDataVo.setAreaCode(deptBean.getAreaCode());
                moveDataVo.setAreaLevel(deptBean.getAreaLevel());

                moveDataVo.setYdfpNumhushu(0);
                moveDataVo.setYdfpNumrenshu(0);
                moveDataVo.setBzstNumhushu(0);
                moveDataVo.setBzstNumrenshu(0);
            }
            deptInfoVoList.add(moveDataVo);
        }
        return deptInfoVoList;
    }

    @Override
    public CommonResultData<List<Map<String, Object>>> getObjPoorAreaTypeStatisticsByMoveType(String areaCode, String moveType) throws
            YJHHException {
        DeptBean sysDeptInfo = commonDataComponent.getSysDeptInfo(areaCode);
        if (sysDeptInfo == null) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        List<DeptBean> subDept = commonDataComponent.getSubDeptByDeptId(sysDeptInfo.getDeptID());

        int subDeptSize = subDept.size();
        if (subDept == null || subDeptSize <= 0 || !DataConsts.getMoveTypeMap().containsKey(moveType)) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }
        //提取子部门ID为数组
        List<String> areaList = new ArrayList();
        List<String> deptIds = new ArrayList<>();
        for (DeptBean deptBean : subDept) {
            deptIds.add(deptBean.getDeptID());
            areaList.add(deptBean.getDeptName());
        }

        //获取按区域分不同类型的搬迁户数
        //获取总的计划搬迁人数-----------------------
        BoolQueryBuilder areacodequery = boolQuery().must(termQuery("deletestate", "0"));
        areacodequery.must(termQuery("stype", "1"));
        areacodequery.must(termsQuery("deptid.keyword", deptIds));
        areacodequery.filter(existsQuery("deptname.keyword"));

        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("pl_pointprograming_inf").setTypes
                ("pointprograming_inf");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(new String[]{"deptid", "deptname", "point_placement_qzjdlipkrs",
                "point_placement_bzrs", "point_placement_strs", "point_placement_allrs"}, null);
        searchSourceBuilder.query(areacodequery);
        FieldSortBuilder sort = new FieldSortBuilder("deptno.keyword");
        searchSourceBuilder.sort(sort);
        searchSourceBuilder.size(10000);
        searchRequestBuilder.setSource(searchSourceBuilder);

        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());

        List<Map<String, Object>> resultList = null;
        //需要根据当前传入的sysDept的deptlevel来判断如果是陕西省则返回陕北、关中、陕南分区汇总，其他情况则返回下属部门的规划人数。
        if (StringUtils.equalsIgnoreCase(DataConsts.PRI_DEPT_LEVEL, sysDeptInfo.getAreaLevel())) {
            //转化结果到规定的区域type中
            resultList = praseDataByAreaType(moveType, searchResponse);
        } else {
            //按部门转化数据到Map
            resultList = praseDataByDeptName(moveType, searchResponse, subDept);
        }


        return new CommonResultData<>(HttpStatus.OK.value(), "suc", resultList);
    }

    @Override
    public CommonResultData<Map<String, String>> getDictInfo(String dictId, String dictpId) throws YJHHException {


        Map<String, String> dicMap = new HashMap<>();
        BoolQueryBuilder query;
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("sy_dict_inf").setTypes("dict_inf");
        if (!XaUtil.isEmpty(dictId)) {
            String[] dictIds = dictId.split(",");
            query = boolQuery().must(termsQuery("dictid", dictIds));
            searchRequestBuilder.setQuery(query);
        } else if (!XaUtil.isEmpty(dictpId)) {
            String[] dictpIds = dictpId.split(",");
            query = boolQuery().must(termsQuery("dictpid", dictpIds));
            searchRequestBuilder.setQuery(query);
        }

        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());

        SearchHit[] searchHits = searchResponse.getHits().getHits();

        for (SearchHit searchHit : searchHits) {
            Map<String, Object> source = searchHit.getSource();
            dicMap.put(searchHit.getId(), DataTools.convertToStr(source.get("dictname")));
        }
        return new CommonResultData<>(HttpStatus.OK.value(), "suc", dicMap);
    }

    @Override
    public CommonResultData<ObjMoveSimpleInfoVo> getPoorObjInfoByIdCard(String idCard) throws YJHHException {
        //获取搬迁户基础表
        QueryBuilder idcardQueryBuilder = QueryBuilders.termQuery("obj_reloca_sfzh.keyword", idCard);
        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_reloca_info").setTypes("reloca_info").setQuery
                (idcardQueryBuilder);

        log.info("reqeust: " + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response:" + searchResponse.toString());

        Map<String, JSONObject> deptInfoMap = initDataFactory.getDeptInfoMap();

        SearchHit[] hits = searchResponse.getHits().getHits();

        if (hits == null || hits.length <= 0) {
            return new CommonResultData<>(HttpStatus.OK.value(), "no data", null);
        }

        Map<String, Object> source = hits[0].getSource();

        String id = source.get("relocationid").toString();


        Map<String, Object> objmovesupinf = (Map<String, Object>) source.get("objmovesupinf");
        Map<String, Object> objmeasuresinfo = (Map<String, Object>) source.get("objmeasuresinfo");
        List<Map<String, Object>> objfamilyinfList = getFamilyMemberByObjId(id);


        ObjMoveSimpleInfoVo simpleInfoVo = new ObjMoveSimpleInfoVo(DataTools.convertToStr(source.get("obj_reloca_hzxm")),
                DataTools.convertToStr(source.get("obj_reloca_yhydbh")),
                DataTools.stringFlagReplace(DataTools.convertToStr(source.get
                        ("obj_reloca_sfzh")), 3, 4, "*"),
                DataTools.stringFlagReplace(DataTools.convertToStr(source.get
                        ("obj_reloca_lxdh")), 3, 4, "*"),
                DataTools.convertToStr(source.get("removaltypename")),
                DataTools.convertToStr(source.get("obj_reloca_whcd")),
                DataTools.convertToStr(source.get("obj_reloca_jtrk")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr(source.get
                        ("obj_reloca_yfwjg"))),
                DataTools.convertToStr(source.get("obj_movesup_ttjzjdmj")) + "㎡",
                DataTools.convertToStr(source.get("provincename")) +
                        DataTools.convertToStr(source.get("cityname")) +
                        DataTools.convertToStr(source.get("countryname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("townname")) +
                        DataTools.convertToStr(source.get("obj_reloca_jtyzz")),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_jgfbzzj")) + "元",
                commonDataComponent.getSysDicValueById(DataTools.convertToStr
                        (objmovesupinf.get("obj_movesup_fwlx"))),
                DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdmc")),
                commonDataComponent.getSysDicValueById(DataTools.convertToStr
                        (objmeasuresinfo.get("obj_measures_bqhsrly"))),
                DataTools.convertToStr(objmovesupinf.get("provincename")) +
                        DataTools.convertToStr(objmovesupinf.get("cityname")) +
                        DataTools.convertToStr(objmovesupinf.get("countryname")) +
                        DataTools.convertToStr(objmovesupinf.get("townname")) +
                        DataTools.convertToStr(objmovesupinf.get("townname")) +
                        DataTools.convertToStr(objmovesupinf.get("obj_movesup_azdmc")));

        //家庭成员信息
        for (Map<String, Object> objfamilyinfMap : objfamilyinfList) {
            if (StringUtils.equalsIgnoreCase(DataTools.convertToStr(objfamilyinfMap.get("obj_relfamily_name")), simpleInfoVo.getOBJ_RELOCA_HZXM())) {
                simpleInfoVo.setOBJ_RELOCA_WHCD(commonDataComponent.getSysDicValueById(DataTools.convertToStr
                        (objfamilyinfMap.get
                                ("obj_relfamily_whcd"))));
            }
        }


        //附件信息
        BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("obat_objectid.keyword", id));
        boolQueryBuilder.must(termQuery("obat_datasourcetype", 1));
        SearchRequestBuilder attachSearchB = esClientManager.getESClient().prepareSearch("obj_attach_inf").setTypes("attach_inf").setQuery
                (boolQueryBuilder);
        log.info("reqeust: " + attachSearchB.toString());
        SearchResponse attachSearchResponse = attachSearchB.execute().actionGet();
        log.info("response:" + attachSearchResponse.toString());

        SearchHit[] searchHits = attachSearchResponse.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> searchHitSource = searchHit.getSource();

            //由于业务库中附件名称存储字段不统一，所以户主照片需要单独处理
            String filePath = DataTools.convertToStr(searchHitSource.get("obat_localpath")) +
                    DataTools.convertToStr(searchHitSource.get("obat_serverpath"));
            if (StringUtils.equalsIgnoreCase(DataTools.convertToStr(searchHitSource.get("obat_datasourcetype")), "1")) {
                filePath += DataTools.convertToStr(searchHitSource.get("obat_attachname"));
                simpleInfoVo.setHuzhuAvatorInfoVo(new AttachInfoVo(DataTools.convertToStr(searchHitSource.get("obat_attachsize")),
                        filePath,
                        DataTools.convertToStr(searchHitSource.get("obat_sourcename")),
                        DataTools.subDateStr(DataTools.convertToStr(searchHitSource.get
                                ("obat_uploadtime")))));
                break;
            }
        }

        return new CommonResultData<>(HttpStatus.OK.value(), "suc", simpleInfoVo);
    }

    /**
     * 按部门转化数据到Map
     *
     * @param moveType
     * @param searchResponse
     */
    private List<Map<String, Object>> praseDataByDeptName(String moveType, SearchResponse searchResponse, List<DeptBean> subDept) {
        //为了防止有些部门没有搬迁数据，所以需要先将部门数据初始化，然后在进行赋值
        LinkedHashMap initMap = new LinkedHashMap();
        for (DeptBean deptBean : subDept) {
            initMap.put(deptBean.getDeptName(), 0);
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit searchHit : hits) {
            Map<String, Object> searchHitSource = searchHit.getSource();
            Integer rs = 0;
            switch (moveType) {
                case DataConsts.RemoveType.YDFP:
                    rs = DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_qzjdlipkrs")));
                    break;
                case DataConsts.RemoveType.BZ:
                    rs = DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_bzrs")))
                            + DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_strs")));
                    break;
                default:
                    rs = DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_allrs")));
                    break;
            }
            String deptid = DataTools.convertToStr(searchHitSource.get("deptid"));
            DeptBean deptBean = commonDataComponent.getDeptByDeptId(deptid);
            if (deptBean == null) {
                continue;
            }

            initMap.put(deptBean.getDeptName(), rs);
        }

        //转化数据格式
        Iterator it = initMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entity = (Map.Entry) it.next();
            Map<String, Object> map = new HashMap<>();
            map.put("xzqh", entity.getKey());
            map.put("data", entity.getValue());
            resultList.add(map);
        }

        return resultList;
    }

    /**
     * 将数据划分为，陕南、陕北、关中进行统计
     *
     * @param moveType
     * @param searchResponse
     * @return
     */
    private List<Map<String, Object>> praseDataByAreaType(String moveType, SearchResponse searchResponse) {
        SearchHit[] hits = searchResponse.getHits().getHits();
        Map<String, Integer> areaRS = new HashMap<>();
        for (SearchHit searchHit : hits) {
            Map<String, Object> searchHitSource = searchHit.getSource();
            Integer rs = 0;
            switch (moveType) {
                case DataConsts.RemoveType.YDFP:
                    rs = DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_qzjdlipkrs")));
                    break;
                case DataConsts.RemoveType.BZ:
                    rs = DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_bzrs")))
                            + DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_strs")));
                    break;
                default:
                    rs = DataTools.stringToInt(DataTools.convertToStr(searchHitSource.get("point_placement_allrs")));
                    break;
            }
            String deptid = DataTools.convertToStr(searchHitSource.get("deptid"));
            DeptBean deptBean = commonDataComponent.getDeptByDeptId(deptid);
            if (deptBean == null) {
                continue;
            }
            String areaType = deptBean.getAreaType();
            if (areaRS.containsKey(areaType)) {
                areaRS.put(areaType, areaRS.get(areaType) + rs);
            } else {
                areaRS.put(areaType, rs);
            }
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        StringTokenizer stringTokenizer = new StringTokenizer(areaType, ",");
        while (stringTokenizer.hasMoreElements()) {
            Map<String, Object> map = new HashMap<>();
            String areaTypeName = stringTokenizer.nextToken();
            Integer planRS = 0;
            if (areaRS.containsKey(areaTypeName)) {
                planRS = areaRS.get(areaTypeName);
            }
            map.put("xzqh", areaTypeName);
            map.put("data", planRS);
            resultList.add(map);
        }
        return resultList;
    }

    /**
     * 根据搬迁户ID获取家庭成员
     *
     * @param objId
     * @throws YJHHException
     */
    private List<Map<String, Object>> getFamilyMemberByObjId(String objId) throws YJHHException {
        BoolQueryBuilder boolQueryBuilder = boolQuery().must(termQuery("relocationid.keyword", objId));
        boolQueryBuilder.must(termQuery("isdelete", "0"));

        SearchRequestBuilder searchRequestBuilder = esClientManager.getESClient().prepareSearch("obj_family_inf").setTypes("obj_family_inf");

        searchRequestBuilder.addSort(new FieldSortBuilder("obj_relfamily_sfzh.keyword"));
        searchRequestBuilder.setQuery(boolQueryBuilder);

        log.info("request=" + searchRequestBuilder.toString());
        SearchResponse searchResponse = searchRequestBuilder.execute().actionGet();
        log.info("response=" + searchResponse.toString());

        SearchHit[] searchHits = searchResponse.getHits().getHits();
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SearchHit searchHit : searchHits) {
            Map<String, Object> objectMap = searchHit.getSource();
            resultList.add(objectMap);
        }
        return resultList;
    }

}
